<?php
declare(strict_types=1);

namespace app\controller\admin;

use app\BaseController;
use app\model\MessageSetting;
use think\facade\Db;
use think\Request;

class MessageConfigController extends BaseController
{
    /**
     * 获取消息配置列表
     */
    public function list()
    {
        try {
            $list = MessageSetting::field('id,type,scene,create_time,update_time')
                ->order('id', 'desc')
                ->select();

            foreach ($list as &$item) {
                $item['type_text'] = $this->getTypeText($item['type']);
                $item['scene_text'] = $this->getSceneText($item['scene']);
            }

            return json([
                'code' => 0,
                'msg' => '获取成功',
                'data' => $list
            ]);
        } catch (\Exception $e) {
            return json(['code' => 1, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * 更新消息配置
     */
    public function update(Request $request,$id)
    {
        Db::startTrans();
        try {
            $data = $request->post();
            
            // 验证数据
            $validate = new \app\validate\MessageConfigValidate();
            if (!$validate->scene('update')->check($data)) {
                return json(['code' => 1, 'msg' => $validate->getError()]);
            }

            $setting = MessageSetting::find($id);
            if (!$setting) {
                return json(['code' => 1, 'msg' => '消息配置不存在']);
            }

            $setting->save([
                'type' => $data['type'],
                'scene' => $data['scene'],
                'update_time' => date('Y-m-d H:i:s')
            ]);

            Db::commit();
            return json(['code' => 0, 'msg' => '更新成功']);
        } catch (\Exception $e) {
            Db::rollback();
            return json(['code' => 1, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * 获取消息类型文本
     */
    private function getTypeText($type)
    {
        $types = [
            1 => '订单通知',
            2 => '订单取消通知',
            3 => '订单揽收通知',
            4 => '订单签收通知',
            5 => '订单退款通知',
            6 => '订单退货通知'
        ];
        return $types[$type] ?? '未知';
    }

    /**
     * 获取场景类型文本
     */
    private function getSceneText($scene)
    {
        $scenes = [
            1 => '用户下单',
            2 => '用户取消订单',
            3 => '用户支付',
            4 => '用户取消支付',
            5 => '用户支付成功',
            6 => '用户支付失败'
        ];
        return $scenes[$scene] ?? '未知';
    }
} 